package com.hunttown.mes.common.utils;

import com.alibaba.fastjson.JSON;

/**
 * FASTJSON 转换工具
 * created by wangjunfu on 2018-11-02
 */
public class FastJsonUtils {

    // 将对象转换成string
    public static String toJSONString(Object object) {
        try {
            return JSON.toJSONString(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 将JSON转换成CLASS
    public static <T> T toJavaObject(JSON json, Class<T> tClass) {
        try {
            return JSON.toJavaObject(json, tClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 将string转换成对象
    public static Object fromJSON(String json) {

        if (StringUtils.isBlank(json) || json.equals("undefined")) {
            return null;
        }

        try {
            return JSON.parse(json);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 将string转换成CLASS
    public static <T> T fromJSON(String json, Class<T> tClass) {

        if (StringUtils.isBlank(json) || json.equals("undefined")) {
            return null;
        }

        try {
            return JSON.parseObject(json, tClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 将JSON转换成CLASS
    public static <T> T fromJSON(JSON json, Class<T> tClass) {
        try {
            return JSON.toJavaObject(json, tClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
